;
(function () {
  'use strict';
  angular.module('services.alarmDataAnalysis.abnormalTransDataMining')
    .service('sumRuleByAlaOTService', sumRuleByAlaOTService);
  function sumRuleByAlaOTService($http, $filter, CoreService, $timeout,CoreLoading) {
    var time = new Date();
    var date = new Date(time.getFullYear(), time.getMonth(), time.getDate() - 1);  //页面时间默认日期的前一天
    //页面参数
    this.params = {
      startTime: date,
      endTime: date,
      businessLineCode: [],  //业务线code
      provincialCompanyCodes: [],  //省公司code
      alarmType: '告警总数'
    };
    this.businessLineList = [];   //业务线列表
    this.provincialCompanyList = [];   //省公司数据列表
    this.alaDataList = [];  //告警数据集合

    this.alarmType = null;  //告警类型输入框绑定值
    this.showSearchPanel = true;//显示查询面板
    this.hideLittleUp=false;  //隐藏查询面板中向上的小箭头
    this.showIcon = true;   //控制显示折线和表格的图标
    this.showDataByHourBtn = false;   //控制是否显示按时刻展示数据的变量
    this.btn = null;   //控制进入查看某一天24个时刻数据面板时  点击’返回‘按钮时 返回的视图（折线或者表格）
    this.viewType = 'chart';//默认折线视图类型
    this.title = null;  //图表和表格显示的标题
    var dayCount = 0; //保存查询数据的总天数
    var chart = null;   //折线图

    var dayCount = 0; //保存查询数据的总天数
    var x = [];
    var timex=null;
    var dataList = [];   //临时数据集合
    this.businessLineNames = [];//图表和表格标题显示业务线名称
    var provincialCompanyNames = [];//图表和表格标题显示省公司名称
    var cproCompanyNames=[];//(选中省公司名称)
    var that = this;
    var param = {}; //临时参数对象
    /**
     * 隐藏查询面板
     */
    this.hideSearchPanel = function () {
      this.showSearchPanel = false;
    };
    /**
     * 清空页面旧值
     */
    this.reset = function () {
      that.showSearchPanel = true;
      that.hideLittleUp=false;
      that.viewType = 'chart';
      that.params.startTime = date;
      that.params.endTime = date;
      that.params.alarmType = '告警总数';
      that.params.businessLineCode = 0;
      that.params.provincialCompanyCodes = [];
      that.alarmType = null;
      that.alaDataList = [];
      that.dataList = [];
      that.showIcon = false;
      that.businessLineNames = [];//图表和表格标题显示业务线名称
      that.businessLineList = [];   //业务线列表
      that.provincialCompanyList = [];   //省公司数据列表
    };
    /**
     * 选中告警总数  告警类型输入框清空
     */
    this.resetAlarmType=function(){
      that.alarmType=null;
    };
    /**
     *@function [initQuery] 初始化頁面下拉查询框，获取系统名称,给系统名称设置默认值，并查询告警级别和状态
     */
    this.initSelectMenu = function () {
      //获取业务线
      $http.get('/sas/common/businessLineQuery')
        .then(function (res) {
          if (res.data.state === '10000' && res.data.data.length >= 1) {
            that.businessLineList = res.data.data;
            that.params.businessLineCode = 0;
          } else {
            CoreService.dialog('查询无数据');
          }
        });

      //获取省公司
      $http.get('/sas/common/provinceQuery')
        .then(function (res) {
          if (res.data.state === '10000' && res.data.data.length >= 1) {
            that.provincialCompanyList = res.data.data;
          } else {
            CoreService.dialog('查询无数据');
          }
        });
      that.search();
    };

    /**
     * 查询 告警数据分省进行分析对比
     */
    this.sendData = null;
    this.search = function () {
      that.hideLittleUp=false;
      //收起查询面板
      if (!that.showSearchPanel) {
        that.showSearchPanel = true;
        return;
      }
      if((that.params.alarmType==='1'&&that.alarmType==null)||(that.params.alarmType==='1'&&that.alarmType==='')){
        that.PageDisplayStyle();
        CoreService.dialog('请输入有效的告警类型');
        return;
      }
      //时间粒度为天时，最多只能查询31天的数据
      var endTime = that.params.endTime.getTime();
      var startTime = that.params.startTime.getTime();
      dayCount = (endTime - startTime) / 1000 / 60 / 60 / 24;
      if (dayCount > 59) {
        CoreService.dialog('只能查询60天内的数据！');
        return;
      }
      CoreLoading.setState(true);
      //copy页面参数 格式化参数
      param = angular.copy(that.params);
      timex=param.startTime;
      param.startTime = $filter('date')(param.startTime, 'yyyy-MM-dd');
      param.endTime = $filter('date')(param.endTime, 'yyyy-MM-dd');
      if (param.alarmType === '1') {
        param.alarmType = that.alarmType;
      }


      //参数省公司传code
      param.provincialCompanyCodes.length || (param.provincialCompanyCodes = that.provincialCompanyList);
      //(选中省公司名称)
      cproCompanyNames = param.provincialCompanyCodes.map(function (obj) {
        return obj.provinceName;
      });
      param.provincialCompanyCodes = param.provincialCompanyCodes.map(function (obj) {
        return obj.provinceCode;
      });
      // (31)省公司 根据Code获取Name,图表展示标题所需 图表横轴坐标展示
      provincialCompanyNames = [];
      angular.forEach(that.provincialCompanyList, function (pro) {
        provincialCompanyNames.push(pro.provinceName);
      });
      //如果选择‘全部’则传所有业务线  否则就传选择的
      param.businessLineCode = param.businessLineCode != 0 ? [param.businessLineCode] : that.businessLineList.map(function (obj) {
        return obj.businessLineCode;
      });
      //业务线 根据Code获取Name,图表展示标题所需
      that.businessLineNames = [];
      angular.forEach(that.businessLineList, function (obj) {
        that.businessLineNames.push(obj.businessLineName);
      });


      //页面标题显示方式
      if (param.alarmType === '告警总数') {
        if(param.startTime===param.endTime){
          that.title = $filter('date')(that.params.startTime, 'yyyy年MM月dd日') + ' 告警数量统计';
        }else{
          that.title = $filter('date')(that.params.startTime, 'yyyy年MM月dd日') + '  至  ' + $filter('date')(that.params.endTime, 'yyyy年MM月dd日') + ' 告警数量统计';
        }

      } else {
        if(param.startTime===param.endTime){
          that.title = $filter('date')(that.params.startTime, 'yyyy年MM月dd日') +' 告警类型为 ' + param.alarmType + ' 告警数量统计';
        }else{
          that.title = $filter('date')(that.params.startTime, 'yyyy年MM月dd日') + '  至  ' + $filter('date')(that.params.endTime, 'yyyy年MM月dd日')+' 告警类型为 ' + param.alarmType + ' 告警数量统计';
        }

      }

      $http.post('/sas/abnormalTrans/dataMining/sumRuleByAlaOutbreakTime/query', param)
        .then(function (res) {
          that.showSearchPanel = false;   //收缩查询面板
          if (res.data.state === '10000' && res.data.data.length >= 1) {
            CoreLoading.setState(false);
            dataList = res.data.data;
            that.changeViewType();  //默认显示折线图表
            that.showIcon = true; //显示表格和折线图标
          } else {
            CoreLoading.setState(false);
            that.PageDisplayStyle();
            CoreService.dialog('查询无数据');
          }

        });

    };

    //初始化折线图数据
    function initChart() {
      chart = echarts.init(document.getElementById('sumRuleByAlaOTChart'));
      var option = {
        animation:false,
        title: {
          text: that.title,
          x: 'center'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {data: ['告警数量'], x: 'right', y: 'center', orient: 'vertical'},
        xAxis: [{type: 'category', boundaryGap: false, data: [], interval:5, splitLine: {show: false}}],
        yAxis: [
          {
            name: '告警数量（条）',
            type: 'value',
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series: [{
          name: '告警数量',
          type: 'line',
          data: []
        }],
        grid: {x: '104', x2: '128'}
      };

      var a = timex;
      x = [];
      var s= new Date(param.startTime).getTime();
      var e= new Date(param.endTime).getTime();
      var count=(e - s ) / 1000 / 60 / 60 / 24;
      for (var i = 0; i <= count; i++) {
        var b = (a / 1000 + 86400 * i) * 1000;
        var time = ($filter('date')(b, 'yyyy/MM/dd'));
        x.push(time);
      }
      option.xAxis[0].data = x;
      angular.forEach(x, function (time) {
        var alarmNumTotal = 0;
        angular.forEach(dataList, function (data) {
          if (data.time === time) {
            alarmNumTotal += data.alarmNum;
          }
        });
        option.series[0].data.push(alarmNumTotal);
      });
      chart.setOption(option);
      $timeout(function(){
        that.sendData=onSubmit();   //导出的图表生成
      },1000);
    };

    /**初始化表格*/
    function initTable() {
      var list = [];
      var row = [];
      var time = $filter('date')(that.params.startTime, 'yyyyMMdd') + '-' + $filter('date')(that.params.endTime, 'yyyyMMdd')
      var busLine = '';
      var provinceNames = '';
      /*var alarmType = param.alarmType;*/
      var alarmType = '';
      if(param.alarmType==='告警总数'){
        alarmType='全部';
      }else{
        alarmType=param.alarmType;
      }
      var alarmNumTotal = 0;
      if (param.provincialCompanyCodes.length === 32) {
        provinceNames = '全部';
      } else {
        angular.forEach(cproCompanyNames, function (obj) {
          provinceNames += obj + ',';
        });
        provinceNames = provinceNames.substring(0, provinceNames.length - 1);
      }
      if (param.businessLineCode.length > 1) {
        busLine = '全部';
      } else {
        angular.forEach(param.businessLineCode, function (code) {
          angular.forEach(that.businessLineList, function (obj) {
            if (obj.businessLineCode === code) {
              busLine = obj.businessLineName;
            }
          });
        });
      }

      angular.forEach(x, function (time) {
        alarmNumTotal=0;
        angular.forEach(dataList, function (data) {
          if (data.time === time) {
            alarmNumTotal += data.alarmNum;
          }
        });
        row = [time, busLine, provinceNames, alarmType, alarmNumTotal];
        list.push(row);
      });
      that.alaDataList = list;
    };

    //查询无数据时页面的样式
    this.PageDisplayStyle = function () {
      that.title='';
      that.viewType='chart';
      that.showSearchPanel = true;   //显示查询面板
      that.hideLittleUp=true;
      that.showIcon = false;  //隐藏表格和折线图标
      dataList = [];  //数据清空
      x=[];
      timex=null;
      that.alaDataList=[];
      chart && chart.clear();  //折线图表数据清空
    }
    //控制显示折线或者表格
    this.changeViewType = function (type) {
      initChart();
      var ta=document.getElementById('ta');
      var cha=document.getElementById('cha');
      that.viewType = type || that.viewType;
      if (that.viewType === 'chart') {
        $timeout(initChart, 0);
        ta.style.backgroundColor = "";
        cha.style.backgroundColor = "#2196F3";
      } else if (that.viewType === 'table') {
        ta.style.backgroundColor = "#2196F3";
        cha.style.backgroundColor = "";
        initTable();
      }
    };
    /**导出excel*/

    function onSubmit () {
      var data = {
        startTime: $filter('date')(param.startTime, 'yyyy-MM-dd'),
        endTime: $filter('date')(param.endTime, 'yyyy-MM-dd'),
        title:that.title,
        provincialCompanyCodes: param.provincialCompanyCodes,  //省公司code
        businessLineCode: param.businessLineCode,  //业务线code
        alarmType:param.alarmType,
        base64s: [chart.getDataURL('png').split(',')[1]],
      };
      return JSON.stringify(data);
    };
  }

  sumRuleByAlaOTService.$inject = ['$http', '$filter', 'CoreService', '$timeout','CoreLoading'];
})();